let pagenum = 1
let pagesize = 10;



const getusers = async() => {
    let pagesize = 10;
    let keyword = document.querySelector('.search').value
    let keyurl;
    if (keyword && keyword) {
        keyurl = `getusers?pagenum=${pagenum}&pagesize=${pagesize}&keyword=${keyword}`;
    } else {
        keyurl = `getusers?pagenum=${pagenum}&pagesize=${pagesize}`;
    }
    const response = await ajax(keyurl)
    let users = response.data
    let total = response.total
    let page_num = Math.floor(total % pagesize == 0 ? total / pagesize : total / pagesize + 1)
    init_page(page_num)
    let tbody = document.querySelector('tbody');
    const userregtime = time => {
        let time1 = time.split('T')[0]
        let time2 = time.split('T')[1].split('.')[0]
        return `${time1} ${time2}`
    }
    tbody.innerHTML = ''
    for (const user of users) {
        let tr = document.createElement('tr');
        tr.innerHTML = `
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.password}</td>
                        <td>${user.gender==0?'女':'男'}</td>
                        <td>${user.email?user.email:'用户未填写'}</td>
                        <td>${user.mobile?user.mobile:'用户未填写'}</td>
                        <td>${userregtime(user.regtime)}</td>
                        <td>
                            <button class="update" onclick="updateuser(${user.id})">编辑</button>
                            <button class="deletebutton"onclick="delete_user(${user.id})" >删除</button>
                        </td>
                        `
        tbody.appendChild(tr)
    }
}

const updateuser = _uid => {
    location.href = `./user_update.html?uid=${_uid}`
}

const init_page = page_num => {
    let page_ul = document.querySelector('.page_ul')
    page_ul.innerHTML = ''
    for (let i = 1; i <= page_num; i++) {
        let li = document.createElement('li')
        li.innerHTML = i
        if (i == pagenum) {
            li.className = 'pagenumactive'
        }
        li.addEventListener('click', function() {
            pagenum = parseInt(li.innerHTML)
            getusers()
        })
        page_ul.appendChild(li)
    }
}

const delete_user = (uid) => {
    let response = ajax(`deleteuser?id=${uid}`, 'DELETE')
    location.href = './users.html'
    alert('删除角色成功')
}

window.onload = function() {
    getusers()
}